import { KV } from "../addons/kv";

interface Storage {
  timestamp: number;
  os: { name: string; release: string };
  uptime: number;
  ips: string[];
  ssh: { state: "stop"; error: string } | { state: "running"; port: number };
  forwards: Record<
    string,
    | { state: "stop"; error: string }
    | { state: "running"; to: { port: number } }
    | undefined
  >;
  crontabs: Record<
    string,
    { state: "stop"; error: string } | { state: "running" } | undefined
  >;
}

const cache: Record<string, Storage | undefined> = {};

function storageKey(id: string) {
  return `storages@${id}`;
}

export async function listStorageId(kv: KV) {
  const prefix = storageKey("");
  const keys = await kv.list(prefix);
  return keys.map((key) => key.substring(prefix.length));
}

export async function getStorage(kv: KV, id: string) {
  if (!(id in cache)) {
    cache[id] = await kv.get(storageKey(id));
    if (cache[id] === undefined) {
      const os = Math.random() < 0.5 ? "ubuntu" : "windows";
      cache[id] = {
        timestamp: Date.now() - Math.random() * 1e9,
        os: {
          name: os,
          release: os === "ubuntu" ? "22.04" : "11",
        },
        uptime: Date.now() - Math.random() * 1e9,
        ips: [],
        ssh: { state: "stop", error: "" },
        crontabs: {},
        forwards: {},
      };
    }
  }
  return cache[id];
}

export async function putStorage(kv: KV, id: string, value: Storage) {
  await kv.put(storageKey(id), value);
  cache[id] = value;
}

export async function deleteStorage(kv: KV, id: string) {
  await kv.delete(storageKey(id));
  delete cache[id];
}
